import React, { useEffect, useMemo, useState } from 'react';
import { Card, Space, Button, Table, Form, Input, DatePicker, Select, Modal, message, Tag, Descriptions } from 'antd';
import { EyeOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;

// 本地存储键名
const LS_KEY = 'authority-operation-logs';

// 操作类型字典（示例）
const OPER_TYPES = [
  { label: '新增', value: 'CREATE' },
  { label: '修改', value: 'UPDATE' },
  { label: '删除', value: 'DELETE' },
  { label: '查询', value: 'QUERY' },
];

const STATE_OPTIONS = [
  { label: '成功', value: 0 },
  { label: '失败', value: 1 },
];

function genInitialData() {
  const arr = [];
  const now = Date.now();
  const fmt = (ms) => {
    const d = new Date(ms);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  };
  const ips = ['192.168.0.2', '10.0.0.33', '172.16.10.8', '127.0.0.1'];
  const locales = ['北京', '上海', '深圳', '杭州'];
  const modules = ['用户管理', '菜单管理', '订单管理', '设备维护'];
  for (let i = 1; i <= 40; i += 1) {
    const type = OPER_TYPES[i % OPER_TYPES.length].value;
    const state = i % 3 === 0 ? 1 : 0;
    const url = `/api/${type.toLowerCase()}/v${(i % 3) + 1}`;
    const params = { id: i, action: type, payload: { a: i, b: i * 2 } };
    const result = { code: state === 0 ? 0 : 500, message: state === 0 ? 'OK' : 'ERROR', data: { id: i } };
    arr.push({
      id: i,
      module: modules[i % modules.length],
      type,
      reqFunc: i % 2 === 0 ? 'POST' : 'GET',
      operator: `admin_${i}`,
      ip: ips[i % ips.length],
      locale: locales[i % locales.length],
      state,
      createTime: fmt(now - i * 3600 * 1000),
      url,
      method: `com.example.${type.toLowerCase()}.Method${i}`,
      rs: JSON.stringify(result),
      querys: JSON.stringify(params),
    });
  }
  return arr;
}

function loadFromLS() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return genInitialData();
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : genInitialData();
  } catch (e) {
    return genInitialData();
  }
}

function saveToLS(list) {
  localStorage.setItem(LS_KEY, JSON.stringify(list));
}

export default function Operation() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState(() => loadFromLS());
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailRow, setDetailRow] = useState(null);

  useEffect(() => {
    form.setFieldsValue({ module: undefined, operator: undefined, type: undefined, dateRange: undefined, state: undefined });
  }, [form]);

  const columns = [
    { title: '操作标题', dataIndex: 'module', key: 'module', width: 180 },
    { title: '业务类型', dataIndex: 'type', key: 'type', width: 120, render: (v) => OPER_TYPES.find((o) => o.value === v)?.label || v },
    { title: '请求方式', dataIndex: 'reqFunc', key: 'reqFunc', width: 120 },
    { title: '操作人员', dataIndex: 'operator', key: 'operator', width: 140 },
    { title: '操作IP', dataIndex: 'ip', key: 'ip', width: 130 },
    { title: '操作地点', dataIndex: 'locale', key: 'locale', width: 140 },
    { title: '操作状态', dataIndex: 'state', key: 'state', width: 120, render: (v) => <Tag color={v === 0 ? 'green' : 'red'}>{v === 0 ? '成功' : '失败'}</Tag> },
    { title: '操作时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
    {
      title: '状态', key: 'actions', width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Button size="small" icon={<EyeOutlined />} onClick={() => onView(record)}>详情</Button>
      )
    }
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys) => setSelectedRowKeys(keys),
  };

  const filteredData = useMemo(() => {
    const { module, operator, type, dateRange, state } = form.getFieldsValue();
    let list = [...dataList];
    if (module) list = list.filter((it) => it.module.includes(module));
    if (operator) list = list.filter((it) => it.operator.includes(operator));
    if (type) list = list.filter((it) => it.type === type);
    if (typeof state === 'number') list = list.filter((it) => it.state === state);
    if (dateRange && dateRange.length === 2) {
      const [start, end] = dateRange;
      const startMs = start?.valueOf();
      const endMs = end?.valueOf();
      list = list.filter((it) => {
        const ms = new Date(it.createTime.replace(/-/g, '/')).getTime();
        return (!startMs || ms >= startMs) && (!endMs || ms <= endMs);
      });
    }
    return list;
  }, [dataList, form]);

  const onSearch = () => {
    message.success('搜索完成');
    setPagination((p) => ({ ...p, current: 1 }));
  };

  const onReset = () => {
    form.resetFields();
    setPagination((p) => ({ ...p, current: 1 }));
  };

  const onView = (row) => {
    setDetailRow(row);
    setDetailOpen(true);
  };

  const onTableChange = (p) => setPagination({ current: p.current, pageSize: p.pageSize });

  return (
    <Card title="操作日志">
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        <Form form={form} layout="inline" onFinish={onSearch}>
          <Form.Item label="操作标题" name="module">
            <Input placeholder="支持模糊匹配" allowClear />
          </Form.Item>
          <Form.Item label="操作人员" name="operator">
            <Input placeholder="支持模糊匹配" allowClear />
          </Form.Item>
          <Form.Item label="业务类型" name="type">
            <Select style={{ width: 160 }} allowClear options={OPER_TYPES} placeholder="全部" />
          </Form.Item>
          <Form.Item label="操作状态" name="state">
            <Select style={{ width: 160 }} allowClear options={STATE_OPTIONS} placeholder="全部" />
          </Form.Item>
          <Form.Item label="时间范围" name="dateRange">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">搜索</Button>
              <Button onClick={onReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          rowKey="id"
          columns={columns}
          dataSource={filteredData}
          loading={loading}
          rowSelection={rowSelection}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            total: filteredData.length,
            showTotal: (t) => `共 ${t} 条`,
          }}
          onChange={onTableChange}
          scroll={{ x: 1200 }}
        />
      </Space>

      <Modal
        title="操作日志详情"
        open={detailOpen}
        onCancel={() => setDetailOpen(false)}
        footer={<Button onClick={() => setDetailOpen(false)}>关闭</Button>}
        width={800}
        destroyOnClose
      >
        {detailRow && (
          <Space direction="vertical" style={{ width: '100%' }} size="middle">
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="操作标题">{detailRow.module}</Descriptions.Item>
              <Descriptions.Item label="请求方式">{detailRow.reqFunc}</Descriptions.Item>
              <Descriptions.Item label="URL">{detailRow.url}</Descriptions.Item>
              <Descriptions.Item label="方法">{detailRow.method}</Descriptions.Item>
              <Descriptions.Item label="操作者">{detailRow.operator}</Descriptions.Item>
              <Descriptions.Item label="IP/地点">{detailRow.ip} / {detailRow.locale}</Descriptions.Item>
              <Descriptions.Item label="状态">{detailRow.state === 0 ? '成功' : '失败'}</Descriptions.Item>
              <Descriptions.Item label="时间">{detailRow.createTime}</Descriptions.Item>
            </Descriptions>
            <div>
              <div style={{ fontWeight: 600, marginBottom: 6 }}>请求参数：</div>
              <pre style={{ background: '#f7f7f7', padding: 12, borderRadius: 6, maxHeight: 240, overflow: 'auto' }}>
                {JSON.stringify(JSON.parse(detailRow.querys || '{}'), null, 2)}
              </pre>
            </div>
            <div>
              <div style={{ fontWeight: 600, marginBottom: 6 }}>返回结果：</div>
              <pre style={{ background: '#f7f7f7', padding: 12, borderRadius: 6, maxHeight: 240, overflow: 'auto' }}>
                {JSON.stringify(JSON.parse(detailRow.rs || '{}'), null, 2)}
              </pre>
            </div>
          </Space>
        )}
      </Modal>
    </Card>
  );
}